package com.cx.common.restful;

import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Builder;
import lombok.Data;

import java.io.Serializable;

/**
 * 统一消息返回
 * @Author :cxy
 */
@Data
@Builder
@ApiModel
//@NoArgsConstructor
//@AllArgsConstructor
@SuppressWarnings("serial")
public class BaseResult<T> implements Serializable{

	@ApiModelProperty(value = "状态码：1成功,其他为失败", required = true)
	private int code;

	@ApiModelProperty(value = "返回数据", required = false)
	private T data;

	@ApiModelProperty(value = "返回提示信息", required = false)
	private String message;

	@Builder
	public BaseResult(ResultCode code) {
		this.code = code.getCode();
		this.message = code.getMessage();
	}

	public static <T> BaseResult<T> success() {
		BaseResult<T> dto = new BaseResult<T>(ResultCode.SUCCESS);
		return dto;
	}
	
	public static <T> BaseResult<T> success(String message) {
		BaseResult<T> dto = new BaseResult<T>(ResultCode.SUCCESS);
		dto.message = message;
		return dto;
	}
	
	public static <T> BaseResult<T> success(T data) {
		BaseResult<T> dto = BaseResult.success();
		dto.setData(data);
		return dto;
	}
	
	public static <T> BaseResult<T> error() {
		BaseResult<T> dto = new BaseResult<T>(ResultCode.FAIL);
		return dto;
	}
	
	public static <T> BaseResult<T> error(String message) {
		BaseResult<T> dto = new BaseResult<T>(ResultCode.FAIL);
		return dto;
	}


	public static <T> BaseResult<T> error(ResultCode resultCode) {
		BaseResult<T> dto = new BaseResult<T>(resultCode);
		return dto;
	}

	public static <T> BaseResult<T> error(ResultCode resultCode, String message) {
		BaseResult<T> dto = new BaseResult<T>(resultCode);
		dto.message = message;
		return dto;
	}
	
	@JsonIgnore
	public boolean isSuccess() {
		return this.code == ResultCode.SUCCESS.getCode();
	}
	
	@JsonIgnore
    public boolean isFail() {
        return !isSuccess();
    }

	// @SuppressWarnings("unchecked")
	// public void setDataIgnoreNull(T data) {
	// if (!(data instanceof String)) {
	// data = (T) JsonUtils.object2StringIgnoreNullField(data);
	// }
	// this.data = data;
	// }


	public BaseResult(int code, T data, String message) {
		this.code = code;
		this.data = data;
		this.message = message;
	}

	public BaseResult() {
	}
}

